<template>
  <BasicModal @register="registerModal" :title="title" :width="800" v-bind="$attrs" @ok="onSubmit">
    <!-- 自定义表单 -->
    <BasicForm @register="registerForm" style="margin: 50px 50px 0 50px" @submit="onSubmit">
      <template #pcaSelect="{ model, field }">
        <a-row class="form-row" :gutter="16">
          <a-col :lg="16">
            <a-form-item :label-col="{ span: 6 }" :wrapper-col="{ span: 60 }">
              <JAreaSelect v-model:province="model.province" v-model:city="model.city" v-model:area="model.district" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="省市区级联多选数值" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
              <span>{{ model }}</span>
            </a-form-item>
          </a-col>
        </a-row>
      </template>
      <!--  #name对应的是formSchemas对应slot(name)插槽    -->
      <template #baiduMaps="{ model, field }">
        <baidu-map class="map" center="银川" :zoom="15">
          <!-- 比例尺控件 -->
          <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
          <!-- 缩放控件 -->
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <!-- 定位控件 -->
          <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :show-address-bar="true" :auto-location="true"></bm-geolocation>

          <!-- 自定义控件 -->
          <bm-control class="map-search-bm-control">
            <!-- 手写输入框 -->
            <div class="flex map-search-container">
              <a-input v-model:value="state.keyword" class="map-search-input" @input="getSearchList"></a-input>
              <a-button type="primary" class="map-search-btn" @click="getSearchList"> 搜索 </a-button>
            </div>
            <!-- 搜索列表 -->
            <div v-if="state.searchListVisible" class="map-search-list">
              <div v-for="(elem, eIndex) of state.searchList" :key="eIndex" class="map-search-item" @click="performPositioning(elem)">
                <p class="map-search-item-title">
                  {{ elem.name }}
                </p>
                <p class="map-search-item-addr">
                  {{ elem.address }}
                </p>
              </div>
            </div>
          </bm-control>

          <!-- 点 https://map.heifahaizei.com/doc/overlay/marker.html -->
          <bm-marker
            v-if="state.isShowSearchPoint"
            :position="{ lng: state.searchPoint.location.lng, lat: state.searchPoint.location.lat }"
            @click="state.spInfoWindow.show = true"
          >
          </bm-marker>

          <!-- 搜索点位弹窗 https://map.heifahaizei.com/doc/overlay/info-window.html#%E5%B1%9E%E6%80%A7 -->
          <bm-info-window
            :show="state.spInfoWindow.show"
            :title="state.spInfoWindow.name"
            :offset="{ width: 0, height: -24 }"
            :position="{ lng: state.spInfoWindow.location.lng, lat: state.spInfoWindow.location.lat }"
            :width="0"
            :max-width="300"
            @close="state.spInfoWindow.show = false"
            @open="state.spInfoWindow.show = true"
          >
            <!-- {{ spInfoWindow }} -->
            <!-- 搜索点位地址 -->
            <p class="sp-info-window-addr">
              {{ state.spInfoWindow.spName }}:<br />
              {{ state.spInfoWindow.spAddress }}
            </p>
            <div class="sp-info-window-header">
              <!-- 搜索点位名称 -->
              <!-- <span class="sp-info-window-name">{{ spInfoWindow.spName }}</span> -->
              <!-- <span class="sp-info-window-around" @click="infoWinGoAround"> 搜周边 </span> -->
            </div>
          </bm-info-window>
        </baidu-map>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref, reactive, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { formSchemas } from './cellAddress.data';
  import { JAreaSelect } from '/@/components/Form';
  import { getDataByCode } from '/@/components/Form/src/utils/areaDataUtil';
  import { apiBaiduList, saveOrUpdate } from './cellAddress.api';
  // 声明 emits
  const emit = defineEmits(['success', 'register', 'search-point-info']);
  const title = ref<string>('');
  const isUpdate = ref<boolean>(false);
  const pca = reactive({
    province: '',
    city: '',
    area: '',
  });
  const state = reactive({
    // 地图缩放级别
    mapZoom: 11,
    // 地图中心点
    mapCenter: {
      lng: 113.88402,
      lat: 22.555259,
    },
    // 是否展示搜索点位
    isShowSearchPoint: false,
    // 搜索点位信息
    searchPoint: {
      lng: 0,
      lat: 0,
    } as any,
    // 搜索点位弹窗信息
    spInfoWindow: {
      show: false,
      spName: '',
      spAddress: '',
      location: {
        lng: 0,
        lat: 0,
      },
    } as any,
    // 搜索关键字
    keyword: '',
    // 搜索列表
    searchList: [] as any[],
    // 搜索列表是否可见
    searchListVisible: false,
  });

  /**
   * 页面初始化
   */
  const initPage = () => {
    // 是否展示搜索点位
    state.isShowSearchPoint = false;
    // 搜索点位信息
    state.searchPoint = {} as any;
    // 搜索点位弹窗信息
    state.spInfoWindow = {
      show: false,
      spName: '',
      spAddress: '',
      location: {
        lng: 0,
        lat: 0,
      },
    };
    // 搜索列表
    state.searchList = [];
    // 搜索列表是否可见
    state.searchListVisible = false;
  };

  /**
   * 获取搜索列表
   */
  const getSearchList = async () => {
    state.searchList = [];
    try {
      const res = await apiBaiduList(state.keyword, '银川');
      if (res.code === 200) {
        state.searchList = res.result;
        // 展示搜索列表
        state.searchListVisible = true;
      }
    } catch (err) {
      console.error('地图 搜索列表 接口请求失败', err);
      state.searchList = [];
      state.searchListVisible = true;
    }
  };

  /**
   * 执行定位
   * @param elem 点位信息，必传
   * @param isCloseSearchList 是否关闭搜索列表，菲必传
   */
  const performPositioning = async (elem: any) => {
    // console.log('执行定位 ---', elem);
    // 隐藏列表
    state.searchListVisible = false;
    // 修改关键字信息
    state.keyword = elem.address ? elem.address : elem.name;
    // 更新外部组件的关键字信息
    emit('search-point-info', elem);
    // 渲染点位
    nextTick(() => {
      // 修改中心点坐标，把当前搜索点，设置为中心点
      state.mapCenter.lng = elem.location.lng;
      state.mapCenter.lat = elem.location.lat;

      // 修改搜索点位坐标
      state.searchPoint = elem;
      // 展示搜索点位
      state.isShowSearchPoint = true;
      console.log('搜索点位的经纬度 ---', state.searchPoint);

      // 设置点位弹窗信息
      showInfoWindow(elem);
    });
    setFieldsValue({
      longitude: elem.location.lng,
      latitude: elem.location.lat,
      title: elem.address,
      province: elem.province,
      city: elem.city,
      district: elem.area,
      address: elem.name,
    });
  };

  /**
   * 展示点位弹窗
   * @param elem 点位信息
   */
  const showInfoWindow = (elem: any) => {
    // 设置点位弹窗信息
    state.spInfoWindow.spName = elem.name; // 标题
    state.spInfoWindow.spAddress = elem.address; // 地址
    state.spInfoWindow.location = elem.location; // 弹框坐标
    // 展示点位信息弹框
    state.spInfoWindow.show = true;
    // 修改搜索点位坐标
    state.searchPoint = elem;
    state.mapCenter = elem.location;
    console.log('展示点位弹窗 ---', state.spInfoWindow);
  };

  // 注册 form
  //update-begin---author:wangshuai ---date:20221123  for：[VUEN-2807]消息模板加一个查看功能------------
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, setProps }] = useForm({
    //update-end---author:wangshuai ---date:20221123  for：[VUEN-2807]消息模板加一个查看功能--------------z
    schemas: formSchemas,
    showActionButtonGroup: false,
  });

  // 注册 modal
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = unref(data.isUpdate);
    title.value = unref(data.title);
    await resetFields();
    await setFieldsValue({ ...data.record });
    await onSearch();
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
    initPage();
  });

  //表单提交事件
  async function onSubmit() {
    try {
      const values = await validate();
      console.log(values);
      setModalProps({ confirmLoading: true });
      // 提交表单
      await saveOrUpdate(values, isUpdate);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  //表单查询事件
  async function onSearch() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // 提交表单
      // await queryBySKU(values.id);
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style scoped>
  .map {
    width: 100%;
    height: 500px;
  }

  .map-search-container {
    display: flex;
    align-items: center;
    padding: 8px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .map-search-input {
    flex: 1;
    margin-right: 8px;
  }

  .map-search-btn {
    white-space: nowrap;
  }

  .map-search-list {
    position: absolute;
    z-index: 999;
    width: 100%;
    max-height: 300px;
    margin-top: 8px;
    overflow-y: auto;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .map-search-item {
    padding: 8px 12px;
    cursor: pointer;
    transition: all 0.3s;
  }

  .map-search-item:hover {
    background: #f5f5f5;
  }

  .map-search-item-title {
    margin: 0;
    font-size: 14px;
    color: #333;
  }

  .map-search-item-addr {
    margin: 4px 0 0;
    font-size: 12px;
    color: #666;
  }

  .sp-info-window-addr {
    margin: 0;
    font-size: 12px;
    color: #666;
  }
</style>
